<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:chapter:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="close"
          >关闭</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">
      </right-toolbar>
    </el-row>
    <div class="app-container">
      <el-row :gutter="20">
        <splitpanes
          :horizontal="this.$store.getters.device === 'mobile'"
          class="default-theme"
        >
          <pane size="16" min-size="16">
            <el-card shadow="never">
              <div slot="header">
                <span> 章节列表 </span>
              </div>
              <el-tree
                :data="chapterList"
                :props="defaultProps"
                node-key="chapterId"
                default-expand-all
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span v-if="data.parentId === -1">
                    {{ data.chapterName }}
                  </span>
                  <span v-else-if="data.parentId === 0">
                    <!-- 第{{ data.sort }}章 · {{ data.chapterName }} -->
                    <i class="el-icon-folder-opened"></i> ·
                    {{ data.chapterName }}
                  </span>
                  <span v-else>
                    <!-- {{ data.sort }} &nbsp;-&nbsp;{{ data.chapterName }} -->
                    <i class="el-icon-notebook-1"></i>&nbsp; · &nbsp;{{
                      data.chapterName
                    }}
                  </span>
                </span>
              </el-tree>
            </el-card>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['system:chapter:edit']"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="single"
                  @click="handleDelete"
                  v-hasPermi="['system:chapter:remove']"
                  >删除</el-button
                >
              </el-col>
            </el-row>
          </pane>
          <pane size="84" min-size="65">
            <el-card shadow="never">
              <div v-if="selectedChapter && selectedChapter.chapterId">
                <el-row :gutter="10" class="mb10">
                  <el-col>选中章节：{{ selectedChapter.chapterName }}</el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-folder-add"
                      size="mini"
                      @click="handleLearning"
                      >上传文档资料</el-button
                    >
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-folder-add"
                      size="mini"
                      >新建知识库</el-button
                    >
                  </el-col>
                </el-row>
                <el-row :gutter="10" class="mb10">
                  <el-col>
                    <el-card class="box-card">
                      <div
                        v-if="
                          selectedChapter.materials &&
                          selectedChapter.materials.length
                        "
                      >
                        <el-row :gutter="10" class="mb8">
                          <el-col :span="1.5">
                            <el-tag>文档资料</el-tag>
                          </el-col>
                        </el-row>
                        <el-table
                          v-loading="loading"
                          :data="selectedChapter.materials"
                        >
                          <el-table-column
                            label="资料id"
                            align="center"
                            prop="materialId"
                          />
                          <el-table-column
                            label="章节id"
                            align="center"
                            prop="chapterId"
                          />
                          <el-table-column
                            label="资料名称"
                            align="center"
                            prop="title"
                          />
                          <el-table-column
                            label="资料内容"
                            align="center"
                            prop="materialType"
                          >
                            <template slot-scope="scope">
                              <dict-tag
                                :options="dict.type.wx_learning"
                                :value="scope.row.materialType"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="文件路劲"
                            align="center"
                            prop="fileUrl"
                          />
                          <el-table-column
                            label="文件大小"
                            align="center"
                            prop="size"
                          />
                          <el-table-column
                            label="资料描述"
                            align="center"
                            prop="description"
                          />
                          <el-table-column
                            label="创建人id"
                            align="center"
                            prop="userId"
                          />
                          <el-table-column
                            label="资料展示首图"
                            align="center"
                            prop="dataImg"
                            width="100"
                          >
                            <template slot-scope="scope">
                              <image-preview
                                :src="scope.row.dataImg"
                                :width="50"
                                :height="50"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="操作"
                            align="center"
                            class-name="small-padding fixed-width"
                          >
                            <template slot-scope="scope">
                              <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="FilePreviews(scope.row)"
                                >查看</el-button
                              >
                              <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdateLearning(scope.row)"
                                >修改</el-button
                              >
                              <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDeleteLearning(scope.row)"
                                >删除</el-button
                              >
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                      <div v-else>
                        <el-empty :image-size="50"></el-empty>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
                <el-row :gutter="10" class="mb10">
                  <el-col>知识题库</el-col>
                  <el-card class="box-card">
                    <el-table :data="selectedChapter.materialss"> </el-table>
                  </el-card>
                </el-row>
              </div>
              <div v-else>请选中具体章节</div>
            </el-card>
          </pane>
        </splitpanes>
      </el-row>
    </div>

    <!-- 添加或修改章节管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openChapter"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formChapter"
        :model="formChapter"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="章节名称" prop="chapterName">
          <el-input
            v-model="formChapter.chapterName"
            placeholder="请输入章节名称"
          />
        </el-form-item>
        <el-form-item label="父章节" prop="parentId">
          <treeselect
            v-model="formChapter.parentId"
            :options="chapterList"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择章节"
            noChildrenText="暂无子级"
            noOptionsText="没有数据"
          />
        </el-form-item>
        <el-form-item label="章节顺序" prop="sort">
          <el-input v-model="formChapter.sort" placeholder="请输入章节顺序" />
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input
            v-model="formChapter.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formChapter.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChapter">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文档资料和视频上传对话框 -->
    <el-dialog
      title="资料上传"
      :visible.sync="openLearning"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="formLearning"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="资料名称" prop="title">
          <el-input v-model="formLearning.title" placeholder="请输入资料名称" />
        </el-form-item>
        <el-form-item label="资料内容" prop="materialType">
          <el-select
            v-model="formLearning.materialType"
            placeholder="请选择资料内容"
          >
            <el-option
              v-for="dict in dict.type.wx_learning"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件路劲" prop="fileUrl">
          <file-upload
            v-model="formLearning.fileUrl"
            :fileSize="fileSize"
            :fileType="fileType"
          />
        </el-form-item>
        <el-form-item label="资料描述" prop="description">
          <el-input
            v-model="formLearning.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="资料展示首图" prop="dataImg">
          <image-upload v-model="formLearning.dataImg" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLearning">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览框 -->
    <el-dialog
      title="文件预览"
      :visible.sync="openporeview"
      width="1000px"
      height="80vh"
      append-to-body
    >
      <FilePreview :src="filesrc" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listChapter,
  getChapter,
  delChapter,
  addChapter,
  updateChapter,
} from "@/api/program/chapter.js";
import {
  addLearning,
  delLearning,
  getLearning,
  updateLearning,
} from "@/api/program/learning.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import FilePreview from "../FilePreview/index.vue";
export default {
  name: "Chapter",
  dicts: ["wx_learning"],
  data() {
    return {
      bankId: null,
      //选中的章节数据
      selectedChapter: {},
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 显示搜索条件
      showSearch: true,
      // 章节管理表格数据
      chapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示章节弹出层
      openChapter: false,
      // 是否显示资料上传弹出层
      openLearning: false,
      //文件预览弹窗
      openporeview: false,
      // 查询参数
      queryParams: {
        bankId: null,
        chapterName: null,
        parentId: null,
        sort: null,
        description: null,
      },
      // 章节表单参数
      formChapter: {
        bankId: null,
      },
      // 资料表单参数
      formLearning: {
        chapterId: null,
      },
      //预览文件路劲
      filesrc: "",
      // 表单校验
      rules: {
        bankId: [
          { required: true, message: "题库id不能为空", trigger: "blur" },
        ],
        chapterName: [
          { required: true, message: "章节名称不能为空", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "父章节id不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "章节顺序不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
        updateBy: [
          { required: true, message: "更新人不能为空", trigger: "blur" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "chapterName",
      },
      //文件上传的大小限制
      fileSize: 10,
      //文件上传的类型限制
      fileType: ["doc", "docx", "ppt", "pptx", "pdf"],
    };
  },
  components: {
    FilePreview,
    Treeselect,
    Splitpanes,
    Pane,
  },
  created() {
    this.bankId = this.$route.params && this.$route.params.bankId;
    this.getList();
  },
  methods: {
    /** 查询章节管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.bankId = this.bankId;
      listChapter(this.queryParams).then((response) => {
        this.chapterList = [];
        const menu = {
          chapterId: 0,
          parentId: -1,
          chapterName: "课程章节(一级目录)",
          children: response.rows,
        };

        this.chapterList.push(menu);
        console.log("response-----", this.chapterList);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.openChapter = false;
      this.openLearning = false;
      this.reset();
    },
    close() {
      const obj = { path: "/bank" };
      this.$tab.closeOpenPage(obj);
    },
    // 表单重置
    reset() {
      this.formChapter = {
        chapterId: null,
        bankId: null,
        chapterName: null,
        parentId: null,
        sort: null,
        description: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null,
      };
      this.resetForm("formChapter");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openChapter = true;
      this.title = "添加章节管理";
    },
    /** 资料上传按钮操作 */
    handleLearning() {
      this.openLearning = true;
    },
    /** 修改章节信息按钮操作 */
    handleUpdate(row) {
      this.reset();
      const chapterId = row.chapterId || this.selectedChapter.chapterId;
      getChapter(chapterId).then((response) => {
        this.formChapter = response.data;
        this.openChapter = true;
        this.title = "修改章节管理";
      });
    },

    /** 修改文档信息按钮操作 */
    handleUpdateLearning(row) {
      const materialId = row.materialId;
      getLearning(materialId).then((response) => {
        this.formLearning = response.data;
        this.openLearning = true;
        this.title = "修改资料管理";
      });
    },
    /** 提交按钮 */
    submitChapter() {
      this.$refs["formChapter"].validate((valid) => {
        if (valid) {
          this.formChapter.bankId = this.bankId;
          if (this.formChapter.chapterId != null) {
            updateChapter(this.formChapter).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.openChapter = false;
              this.getList();
            });
          } else {
            addChapter(this.formChapter).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.openChapter = false;
              this.getList();
            });
          }
        }
      });
    },
    //上传资料文档
    submitLearning() {
      this.formLearning.chapterId = this.selectedChapter.chapterId;
      addLearning(this.formLearning).then((response) => {
        this.$modal.msgSuccess("上传成功");
        this.openLearning = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chapterIds = this.selectedChapter.chapterId;
      const chapterName = this.selectedChapter.chapterName;
      this.$modal
        .confirm('是否确认删除"' + chapterName + '"章节？')
        .then(function () {
          return delChapter(chapterIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //过滤选择的数据
    normalizer(node) {
      // 1. 保证一定是数组（null→[]）
      if (!node.children) node.children = [];
      // 2. 返回给组件
      return {
        id: node.chapterId,
        label: node.chapterName,
        children: node.children.length ? node.children : undefined, // 空数组给 undefined
      };
    },
    FilePreviews(row) {
      console.log("row", row);
      this.openporeview = true;
      this.filesrc = row.fileUrl;
    },

    //目录点击事件
    handleNodeClick(data, node, component) {
      if (data.parentId === -1) {
        this.single = true;
        this.selectedChapter = {};
      } else {
        this.single = false;
        this.selectedChapter = data;
      }
    },

    handleDownload(url, fileName) {
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    //删除文档资料
    handleDeleteLearning(row) {
      const materialIds = row.materialId;
      this.$modal
        .confirm('是否确认删除资料上传编号为"' + materialIds + '"的数据项？')
        .then(function () {
          return delLearning(materialIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped></style>
